package com.huiminpay.merchant.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.exception.BusinessCast;
import com.huiminpay.common.cache.exception.BusinessException;
import com.huiminpay.common.cache.util.PhoneUtil;
import com.huiminpay.merchant.convert.MerchantConvert;
import com.huiminpay.merchant.entity.Merchant;
import com.huiminpay.merchant.entity.Store;
import com.huiminpay.merchant.mapper.MerchantMapper;
import com.huiminpay.user.api.TenantService;
import com.huiminpay.user.api.dto.tenant.CreateTenantRequestDTO;
import com.huiminpay.user.api.dto.tenant.TenantDTO;
import com.yh.merchant.api.MerchantServiceApi;
import com.yh.merchant.dto.MerchantDTO;
import com.yh.merchant.dto.StaffDTO;
import com.yh.merchant.dto.StoreDTO;
import com.yh.merchant.dto.StoreStaffDTO;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: HWW
 * @Date: 2021/8/1715:40
 * @Desc:
 */
@Service
public class MerchantService implements MerchantServiceApi {



    @Autowired
    private MerchantMapper merchantMapper;

    @Reference
    private TenantService tenantService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private StaffService staffService;



    /**
     * 搭建服务后的第一次测试
     *
     * @param id
     * @return
     */
    @Override
    public MerchantDTO queryMerchantById(Long id) {

        Merchant merchant = merchantMapper.selectById(id);

        MerchantDTO merchantDTO = new MerchantDTO();

        BeanUtils.copyProperties(merchant, merchantDTO);
        return merchantDTO;
    }

    /**
     * 1.商户注册服务
     * 2.调用
     * @param merchantDTO
     * @return
     * @throws BusinessException
     */
    @Override
    public MerchantDTO registerMerchant(MerchantDTO merchantDTO) throws BusinessException {

        //1.校验参数-start
        if (merchantDTO == null) {
            BusinessCast.cast(CommonErrorCode.E_100108);
        }
        //手机号非空校验
        if (StringUtils.isEmpty(merchantDTO.getMobile())) {
            BusinessCast.cast(CommonErrorCode.E_100112);
        }
        //手机号合法性校验
        if (!PhoneUtil.isMatches(merchantDTO.getMobile())) {
            BusinessCast.cast(CommonErrorCode.E_100109);
        }
        //联系人非空校验
        if (StringUtils.isBlank(merchantDTO.getUsername())) {
            BusinessCast.cast(CommonErrorCode.E_100110);
        }
        // 密码非空校验
        if (StringUtils.isBlank(merchantDTO.getPassword())) {
            BusinessCast.cast(CommonErrorCode.E_100111);
        }
        //校验商户手机号码唯一
        Integer count = merchantMapper.selectCount(new LambdaQueryWrapper<Merchant>()
                .eq(Merchant::getMobile,merchantDTO.getMobile()));
        if(count>0){
            throw  new BusinessException(CommonErrorCode.E_100113);
        }

        //2.创建租户-start
        CreateTenantRequestDTO createTenantRequestDTO = new CreateTenantRequestDTO();
        createTenantRequestDTO.setName(merchantDTO.getUsername());//设置租户名称
        createTenantRequestDTO.setTenantTypeCode("huimin-merchant");//租户类型编码-表示该租户类型是商户
        createTenantRequestDTO.setMobile(merchantDTO.getMobile());//设置租户管理员登录手机号
        createTenantRequestDTO.setUsername(merchantDTO.getUsername()); //设置租户管理员登录用户名
        createTenantRequestDTO.setPassword(merchantDTO.getPassword());//租户管理员登录密码
        createTenantRequestDTO.setBundleCode("huimin-merchant");
        //如果租户在SaaS已经存在，SaaS直接 返回此租户的信息，否则进行添加
        TenantDTO tenantAndAccount = tenantService.createTenantAndAccount(createTenantRequestDTO);

        //3.添加商户
        Merchant merchant = MerchantConvert.INSTANCE.dto2entity(merchantDTO);
        merchant.setTenantId(tenantAndAccount.getId());//设置租户ID
        merchant.setAuditStatus("0");//设置审核状态0‐未申请,1‐已申请待审核,2‐审核通过,3‐审核拒绝
        // TODO 判断商户的手机号是否已在已注册的商户列表中
        merchantMapper.insert(merchant);

        //4.添加门店
        StoreDTO storeDTO = new StoreDTO();
        storeDTO.setStoreName("根门店");
        storeDTO.setMerchantId(merchant.getId());//商户id（租户ID）
        StoreDTO store = storeService.createStore(storeDTO);

        //5.添加员工
        StaffDTO staffDTO = new StaffDTO();
        staffDTO.setMerchantId(merchant.getId());//设置商户ID
        staffDTO.setMobile(merchantDTO.getMobile());//设置手机号
        staffDTO.setUsername(merchantDTO.getUsername());//设置用户名
        staffDTO.setStoreId(store.getId());//给员工设置所属门店id
        StaffDTO staff = staffService.createStaff(staffDTO);

        //6.为门店设置管理员--门店绑定员工
        staffService.bindStaffToStore(store.getId(),staff.getId());

        //saas信息
        merchantDTO = MerchantConvert.INSTANCE.entity2dto(merchant);
        return merchantDTO;
    }

    /**
     * 资质申请
     * @param id
     * @param merchantDTO
     * @return
     */
    @Override
    public MerchantDTO applyMerchant(Long id, MerchantDTO merchantDTO) {
        //校验参数
        if(merchantDTO == null || StringUtils.isEmpty(id+"")){
            BusinessCast.cast(CommonErrorCode.E_100101);
        }
        //根据商户ID获取商户信息
        Merchant merchantDB = merchantMapper.selectById(id);
        if(merchantDB==null){
            BusinessCast.cast(CommonErrorCode.E_100110);
        }

        Merchant merchant = MerchantConvert.INSTANCE.dto2entity(merchantDTO);
        merchant.setId(id);
        merchant.setMobile(merchantDB.getMobile());
        //设置审核状态0‐未申请,1‐已申请待审核,2‐审核通过,3‐审核拒绝
        merchant.setAuditStatus("1");

        merchantMapper.updateById(merchant);

        return MerchantConvert.INSTANCE.entity2dto(merchant);
    }

}
